package com.cn.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cn.gmall.client.CartFeignClient;
import com.cn.gmall.common.constant.RedisConst;
import com.cn.gmall.common.execption.GmallException;
import com.cn.gmall.common.result.Result;
import com.cn.gmall.common.result.ResultCodeEnum;
import com.cn.gmall.common.util.AuthContextHolder;
import com.cn.gmall.model.cart.CartInfo;
import com.cn.gmall.model.order.OrderDetail;
import com.cn.gmall.model.order.OrderInfo;
import com.cn.gmall.order.service.OrderService;
import com.cn.gmall.product.client.ProductFeignClient;

import org.apache.commons.lang.StringUtils;

import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import java.util.concurrent.CompletableFuture;



@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Resource
    private OrderService orderService;
    /***
     * 需要去写配置类进行线程数等的配置
     */
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private ProductFeignClient productFeignClient;
    @Resource
    private CartFeignClient cartFeignClient;
    @Resource
    private RedisTemplate redisTemplate;
//

    /** 给秒杀使用 (此时不需要判断 校验库存 以及价格)
     * /api/order/inner/seckill/submitOrder
     * @param orderInfo
     * @return
     */
    @PostMapping("/inner/seckill/submitOrder")
public Long submitOrderReturnId(@RequestBody OrderInfo orderInfo){
return orderService.submitOrder(orderInfo);
}

    /***  拆单供给 库存管理系统使用
     * 返回格式 : [{"wareId":"1","skuIds":["21","22","24"]},{"wareId":"2","skuIds":["27"]}]
     *
     * http://localhost:8204/api/order/orderSplit
     * @param request
     * @return
     */
    @PostMapping("/orderSplit")
    public String orderSplit(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");
        //拆单

        List<OrderInfo> subOrderList = orderService.orderSplit(orderId, wareSkuMap);
//      转换数据类型
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(subOrderList)) {
            for (OrderInfo orderInfo : subOrderList) {
//               转换对象
                Map<String, Object> orderMap = orderService.initWareOrder(orderInfo);
                mapList.add(orderMap);
            }
        }
//        处理
        return JSONObject.toJSONString(mapList);


    }


    /***
     * /api/order/inner/getOrderInfo/{orderId}
     * 根据订单Id 查询订单详情信息
     * @param orderId
     * @return
     */
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public Result<OrderInfo> getOrderInfo(@PathVariable Long orderId) {
        OrderInfo orderInfo = orderService.getOrderById(orderId);

        return Result.ok(orderInfo);
    }


    /**
     * 查看我的订单
     * /api/order/auth/{page}/{limit}
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/auth/{page}/{limit}")
    public Result findOrdersByUserId(@PathVariable Long page,
                                     @PathVariable Long limit,
                                     HttpServletRequest request) {

        //封装分页对象
        Page<OrderInfo> orderInfoPage = new Page<>(page, limit);
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //调用service查询
        IPage<OrderInfo> orderInfoIPage = orderService.findOrdersByUserId(userId, orderInfoPage);

        return Result.ok(orderInfoIPage);

    }


    /**
     * 提交订单
     * /api/order/auth/submitOrder
     *
     * @return
     */

    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //设置用户id
        orderInfo.setUserId(Long.parseLong(userId));
        //获取流水号
        String tradeNo = request.getParameter("tradeNo");
        //校验流水号
        boolean checkTradeCode = orderService.checkTradeCode(userId, tradeNo);
        //判断
        if (!checkTradeCode) {
            return Result.fail().message("请勿重复提交");
        }
        //定义收集异常的集合 每一个订单项都进判断是否能够满足
        List<String> errorList = new ArrayList<>();


        //定义集合，收集异步对象
        List<CompletableFuture> futureList = new ArrayList<>();
        for (OrderDetail orderDetail : orderInfo.getOrderDetailList()) {

            CompletableFuture<Void> checkStockFuture = CompletableFuture.runAsync(() -> {
                //校验库存
                //orderDetail具体商品信息
                boolean result = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                //判断
                if (!result) {

                    errorList.add(orderDetail.getSkuId() + " " + orderDetail.getSkuName() + "库存不足");
                }
            }, threadPoolExecutor);
// 库存
            futureList.add(checkStockFuture);

//     实时价格的校验
            CompletableFuture<Void> checkPriceFuture = CompletableFuture.runAsync(() -> {

                //校验价格
                BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                //获取当前订单中商品的价格
                BigDecimal orderPrice = orderDetail.getOrderPrice();
                //比较
                if (orderPrice.compareTo(skuPrice) != 0) {

                    //获取所有商品最新价格
                    List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
                    //更新redis  user:1:cart  skuId  cartInfo
                    for (CartInfo cartInfo : cartCheckedList) {
                        redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);

                    }
                    errorList.add(orderDetail.getSkuId() + " " + orderDetail.getSkuName() + "价格有变动,请从购物车重新提交！！");

                }
            }, threadPoolExecutor);

            futureList.add(checkPriceFuture);
        }

        //异步编排 allOf(可变参/相同类型搞的数组)
        CompletableFuture.allOf(
                futureList.toArray(new CompletableFuture[futureList.size()])
        ).join();

        //判断结果
        if (errorList.size() > 0) {

            return Result.fail().message(StringUtils.join(errorList, ","));

        }

        //调用service保存
        Long orderId = orderService.submitOrder(orderInfo);

        //删除流水号
        orderService.deleteTradeNo(userId);

        return Result.ok(orderId);
    }


    /**
     * 去结算
     * /api/order/auth/trade
     *
     * @param request
     * @return
     */

    @GetMapping("/auth/trade")
    public Result toTrade(HttpServletRequest request) {

        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)) {
            throw new GmallException("订单结算没有userId 无法定位用户", ResultCodeEnum.SECKILL_FAIL.getCode());
        }
        Map<String, Object> resultMap = orderService.toTrade(userId);

        return Result.ok(resultMap);

    }


}
